package com.lwq.lwqmicoservice.gateway;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lwq.lwqmicoservice.common.model.RelRolePermission;
import com.lwq.lwqmicoservice.common.model.SysPermission;
import com.lwq.lwqmicoservice.framework.mapper.PermissionMapper;
import com.lwq.lwqmicoservice.framework.mapper.RolePermissionMapper;
import com.lwq.lwqmicoservice.gateway.util.AnnotationManager;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

@SpringBootApplication
@EnableDiscoveryClient
@MapperScan(value="com.lwq.lwqmicoservice.framework.mapper")
@ComponentScan(basePackages = {"com.lwq.lwqmicoservice.common.service","com.lwq.lwqmicoservice"})
public class LwqMicoServiceGatewayApplication {

    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Value("${spring.application.name}")
    private String applicationName;

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    public static void main(String[] args) {
        SpringApplication.run(LwqMicoServiceGatewayApplication.class, args);
    }

    /**
     * 项目启动的时候 把所有权限注解更新到权限表里
     */
    @PostConstruct
    public void initPermissions(){
        handlePermission();
    }

    @Transactional(rollbackFor = Exception.class)
    public void handlePermission(){
        this.logger.info("开始同步权限.....");
        List<SysPermission> permissionList = permissionMapper.selectList(new QueryWrapper<SysPermission>().eq("project",applicationName));
        List<SysPermission> permissionByAnno = AnnotationManager.getPermissionByAnno();
        //过滤出要删除的权限
        List<SysPermission> removeList = permissionList.stream().filter(e ->
                permissionByAnno.stream().filter(i -> i.getName().equals(e.getName()) &&
                        i.getCode().equals(e.getCode()) &&
                        i.getType().equals(e.getType())).count()<1).collect(Collectors.toList());
        removeList.forEach(e -> {
            rolePermissionMapper.delete(new QueryWrapper<RelRolePermission>().eq("permission_id", e.getId()));
            permissionMapper.deleteById(e.getId());
        });
        //过滤出要新增的权限
        List<SysPermission> saveList = permissionByAnno.stream().filter(e ->
                        permissionList.stream().filter(i -> i.getName().equals(e.getName())
                                && i.getCode().equals(e.getCode()) && i.getType().equals(e.getType())).count()<1)
                .collect(Collectors.toList());
        //去重
        saveList = saveList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<SysPermission>(Comparator.comparing(o -> o.getName() + "#" + o.getType() + "#" + o.getCode()))), ArrayList::new));
        saveList.forEach(e -> {
            e.setProject(applicationName);
            permissionMapper.insert(e);
        });
        this.logger.info("同步结束");
    }

}
